package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.compete;

import cn.dev33.satoken.stp.StpUtil;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.compete.CompeteAdvanceBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysFiles;
import com.xiaoxu.intranetweb.util.PermissionCheck;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.WebFunctionUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Map;

@RestController
@RequestMapping(value = "/competeAdvance")
public class CompeteAdvanceController {
    @Autowired
    private CompeteAdvanceBu competeAdvanceBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private WebFunctionUtil webFunctionUtil;

    @GetMapping("/competeAdvance")
    @PermissionCheck("competeAdvance_competeAdvance")
    public SzResult competeAdvance(@RequestParam String id,
                                   @RequestParam(required = false) String archivedStatus,
                                   @RequestParam(required = false) String OpenMinBidStatus,
                                   @RequestParam(required = false) String priceShowStatus,
                                   HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");      String plantId = request.getHeader("Plant-Id");
        competeAdvanceBu.competeAdvance(id, archivedStatus, OpenMinBidStatus, priceShowStatus, token,plantId);
        return SzResult.Success();
    }

    //    上传文件接口
    @PostMapping ("/upload")
    public SzResult upload(@RequestParam("file") MultipartFile file,
                           @RequestParam(required = false) String connId, HttpServletRequest request,
                           HttpServletResponse response) throws Exception {
        String token = request.getHeader("Authorization");
        return competeAdvanceBu.uploadFile(file, connId, token);
    }


    //    下载文件接口
    @GetMapping("/download")
    public void downloadFile(@RequestParam("fileId") String fileId, HttpServletResponse response, HttpServletRequest request) throws IOException {
        try {
            SysFiles sysFiles = competeAdvanceBu.downloadFile(fileId);
            Path path = Paths.get(sysFiles.getFilePath() + sysFiles.getId() + "." + sysFiles.getFileType());
            String fileName = sysFiles.getFileName();
            InputStream inputStream = new BufferedInputStream(Files.newInputStream(new File(path.toString()).toPath()));
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/x-download");
            response.setHeader("Content-Length", "" + path.toFile().length());
            response.setHeader("Content-Disposition", "attachment; filename*=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] bytes = new byte[1024];
            int len = 0 ;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            response.setStatus(500);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            e.printStackTrace();
        }
    }

    //    删除文件接口
    @GetMapping("/deleteFile")
    @PermissionCheck("file_deleteFile")
    public SzResult deleteFile(@RequestParam("id") String id, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            return competeAdvanceBu.deleteFile(id);
        } catch (Exception e) {
            e.printStackTrace();
            return SzResult.error(e.getMessage());
        }
    }

    //    预览文件接口
    @GetMapping("/previewFile")
    public SzResult previewFile(@RequestParam("id") String id, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
     /*   if (!userInfoDao.getUserPermissionWeb(StpUtil.getLoginIdByToken(token).toString()).containsKey("file_previewFile")) {
            return SzResult.error("您没有预览文件的权限");
        }*/
        try {
            Path path = competeAdvanceBu.previewFile(id);
            if (path == null) {
//               无文件
                return SzResult.error("无文件或改文件类型暂不支持预览");
            }
//            根据path拿到文件数据
            InputStream inputStream = new BufferedInputStream(new FileInputStream(new File(path.toString())));
//            转base64
            OutputStream outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            String base64 = Base64.getEncoder().encodeToString(((ByteArrayOutputStream) outputStream).toByteArray());
//            关闭流
            outputStream.flush();
            outputStream.close();
            inputStream.close();
//            返回数据
            return SzResult.success(base64);
        } catch (Exception e) {
            e.printStackTrace();
            return SzResult.error(e.getMessage());
        }
    }

    /**
     * 获取文件
     */
    @GetMapping("/getFile")
    public SzResult getFile() throws Exception {
        return competeAdvanceBu.getFile();
    }
}
